package com.bdqn.ch02.service;

import com.bdqn.ch02.pojo.SysUser;
import com.bdqn.ch02.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService{

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    public Page<SysUser> findPageByMap(Map param, Pageable pageable) {
        return sysUserRepository.findAll(new Specification<SysUser>() {
                @Override
            public Predicate toPredicate(Root<SysUser> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {

                List<Predicate> predicates = new ArrayList<>();
                if (param.get("usrName") != null) { //动态 SQL
                    predicates.add(criteriaBuilder.like(root.get("usrName"), "%" + param.get("usrName") + "%"));
                }
                if (param.get("roleId") != null) {
                    predicates.add(criteriaBuilder.equal(root.get("usrRoleId"), param.get("ro leId")));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
    }
}